import { createContext, useContext } from 'react'

export type Theme = 'light' | 'dark' | 'system'

export const ThemeContext = createContext<Theme>('system')

const useGetTheme = () => useContext(ThemeContext)

const ThemeComp = () => {
  const theme = useGetTheme()
  return <div>主题是：{theme}</div>
}

export type Complex = {
  kind: string
}

// 当没有合理的默认值时，可显式设置 ContextShape | null
// 上下文在类型中创建为 `| null`，以准确反映默认值
export const ComplexContext = createContext<Complex | null>(null)

const useGetComplexObject = () => {
  const object = useContext(ComplexContext)
  // 但是需要在context consumer消除null的类型，在运行hook时检查它的存在，不存在时抛出错误
  if(!object) {throw new Error('useGetComplexObject must be used within a Provider')}
  return object
}

const ComplexComp = () => {
  const object = useGetComplexObject()
  return <div>current object: {object.kind}</div>
}

export default ThemeComp

export {
  ComplexComp
}